package com.xopencode.netty.heima;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;

/**
 * @author Mcb
 * @date 2022/5/21
 * @apiNote Netty服务端详细介绍
 */
@Slf4j
public class EventLoopIoClient2 {
    public static void main(String[] args) throws InterruptedException {
        EventLoopGroup group = new NioEventLoopGroup();
        //创建客户端的启动助手
        ChannelFuture channelFuture = new Bootstrap()
                .group(group)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<NioSocketChannel>() {
                    // 连接建立后被调用
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new StringEncoder());
                    }
                })
                //异步非堵塞，main发起调用 真正执行 connet 是nio线程
                .connect(new InetSocketAddress("localhost", 9090));

        //方式一
        /*channelFuture.sync(); //堵塞当前线程，直到nio线程连接建立完毕
        Channel channel = channelFuture.channel();
        log.debug("{}", channel);
        channel.writeAndFlush("hello world");*/

        //方式二
        channelFuture.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                Channel channel = future.channel();
                log.debug("{}------------", channel);
                channel.writeAndFlush("hello world");
            }
        });

        //System.out.println("与服务端的连接对象---" + channel);
        //System.out.println("");
    }
}
